const express = require('express');
const imgModel = require('../modules/img_tab')
const imgRouter = express.Router()

//插入图片
imgRouter.post('/upload', async (req, res, next) => {
    try {
        const { url, user_id, description, create_time } = req.body
        const imgs = await imgModel.findAll({ raw: true })
        let img_id = imgs.length > 0 ? imgs.sort((a, b) => b.img_id - a.img_id)[0].img_id + 1 : 1
        
        const result = await imgModel.create({ img_id,url,user_id,description,create_time });
        res.json({
            code: 1,
            msg: '请求成功'
        })
    } catch (err) {
        next(err)
    }
})
//根据user_id查找所有图片
imgRouter.get('/search/all',async(req,res,next) => {
    try{
        const { user_id } = req.query
        const result = await imgModel.findAll({
            raw:true,
            where:{
                is_delete:0,
                user_id
            }
        })
        res.json({
            code:1,
            msg:'请求成功',
            data:result
        })
    }catch(err){
        next(err)
    }
})
// 错误处理中间件
imgRouter.use((err, req, res, next) => {

    res.status(500).json({
      code: 0,
      msg: '服务器内部错误',
    });
  });
module.exports = imgRouter